package com.liry.security.config;

import com.alibaba.fastjson.JSON;
import com.liry.security.domain.vo.ResponseData;
import com.liry.security.domain.vo.UserView;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 登录成功处理器
 * 序列化处理
 *
 * @author ALI
 * @since 2023/6/1
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        // 将成功后的会话id设置到响应，以便在链里的过滤器能够拿到
        String token = UUID.randomUUID().toString();
        httpServletResponse.setHeader(HttpHeaders.AUTHORIZATION, token);
        // 设置响应的格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResponseData<CustomUser> result = new ResponseData<>();
        CustomUser user = (CustomUser) authentication.getPrincipal();
        UserView temp = new UserView(user, token);
        result.setData(temp);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
    }
}
